<?php  
class Student 
{ 
    private $surname; 
    private $first_name; 
    private $emails; 
    private $grades; 
    function __construct($surname, $first_name) 
    { 
        $this->surname = $surname; 
        $this->first_name = $first_name; 
        $this->emails = array(); 
        $this->grades = array(); 
    }
    function add_email($which, $address) 
    { 
        $this->emails[$which] = $address; 
    } 
    function add_grade($grade) 
    { 
        $this->grades[] = $grade; 
    }
    
    // 计算平均分的方法
    function average()
    {
        $total = 0; 
        foreach ($this->grades as $value) 
            $total += $value; 
        // 避免除以零错误，当没有成绩时返回0
        return count($this->grades) > 0 ? $total / count($this->grades) : 0;
    }
    
    // 重写toString方法
    function toString() 
    { 
        $result = $this->first_name . ' ' . $this->surname; 
        $result .= ' (' . $this->average() . ")\n"; 
        foreach ($this->emails as $which => $what) 
            $result .= $which . ': ' . $what . "\n"; 
        $result .= "\n"; 
        return $result;
    }
}